package com.polaris.live.im.sfs.processor.impl

import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.im.manager.ImCallManager
import com.polaris.live.im.sfs.COMMAND_CALL_ANSWER
import com.polaris.live.im.sfs.COMMAND_CALL_CANCEL
import com.polaris.live.im.sfs.COMMAND_CALL_END
import com.polaris.live.im.sfs.COMMAND_CALL_NO_ANSWER
import com.polaris.live.im.sfs.COMMAND_CALL_REFUSE
import com.polaris.live.im.sfs.COMMAND_CALL_START
import com.polaris.live.im.sfs.COMMAND_CALL_START_WAIT
import com.polaris.live.im.sfs.COMMAND_LIVE_MESSAGE
import com.polaris.live.im.sfs.LIVE_NOTICE_MESSAGE
import com.polaris.live.im.sfs.LIVE_TOAST_MESSAGE
import com.polaris.live.im.sfs.TYPE_CALL_MESSAGE
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.processor.AbstractMessageProcessor
import com.polaris.live.im.utils.sfsObjectLiveMessageRequest
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.manager.MNotificationManager
import com.polaris.live.resp.event.CallEndEvent
import com.polaris.live.ui.live.activity.CallVideoActivity
import com.polaris.live.ui.live.activity.LiveVideoActivity
import com.polaris.live.ui.party.activity.PartyAnchorActivity
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import org.greenrobot.eventbus.EventBus

/**
 * 通话事件
 *
 * @author Created by lucas on 2023/10/19 16:35
 * @since 1.0.0
 */
class CallEventMessageProcessor : AbstractMessageProcessor() {

    private val msgIdList = mutableSetOf<String>()

    override fun shouldProcess(type: Int, command: String): Boolean {
        return command in commands
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        when (command) {
            //通话公屏消息
            COMMAND_LIVE_MESSAGE -> {
                val liveMessage = argument.getData {
                    sfsObjectLiveMessageRequest(it)
                }
                if (liveMessage?.businessType == TYPE_CALL_MESSAGE) {
                    ImCallManager.onPublicMessage(liveMessage)
                }
            }
            // 通话开始，不需要等待
            COMMAND_CALL_START -> {
                onCallStart(command, argument, false)
            }
            // 通话开始 弹起等待
            COMMAND_CALL_START_WAIT -> {
                onCallStart(command, argument, true)
            }
            //通话同意
            COMMAND_CALL_ANSWER -> {
                if (!resolvedMsgId(argument)) {
                    ImCallManager.onMessage(command, argument, true)
                }
            }
            //其他的直接向下转发
            else -> {
                val delayMessage = when (command) {
                    COMMAND_CALL_REFUSE -> true
                    else -> false
                }

                ImCallManager.onMessage(command, argument, delayMessage)
            }
        }
    }

    private suspend fun onCallStart(
        command: String,
        argument: DataArgument,
        needAgree: Boolean,
    ) {
        if (resolvedMsgId(argument)) {
            return
        }

        val callBean = argument.getData<CallSignalingMessage>() ?: return

        if (!AppUtils.isAppForeground()) { //在后台才显示通知
            MNotificationManager.sendCallNotification(callBean)
        }

        when (LiveStateManager.getState()) {
            LiveConst.State.NONE -> {
                //直接唤起
                gotoCallApply(needAgree, callBean)
            }

            LiveConst.State.LIVE_AND_MATCH -> {
                //查询当前是否在直播，防止状态错误
                val liveVideoActivity = ActivityUtils.getActivityList().find {
                    it is LiveVideoActivity
                }
                if (liveVideoActivity != null) {
                    //正常下发消息
                    ImCallManager.onMessage(command, argument)

                    EventBus.getDefault().post(CallEndEvent())
                } else {
                    //如果为空说明状态错误，直接拉起
                    gotoCallApply(needAgree, callBean)
                }
            }

            LiveConst.State.CALL -> {
                //查询当前是否在通话，防止状态错误
                val videoActivity = ActivityUtils.getActivityList().find {
                    it is CallVideoActivity || it is LiveVideoActivity
                }
                //如果当前是通话状态，但是通话页面没有出现说明出现状态错乱
                if (videoActivity == null) {
                    gotoCallApply(needAgree, callBean)
                }
            }

            LiveConst.State.PARTY -> {
                //查询当前是否语聊房
                val partyAnchorActivity = ActivityUtils.getActivityList().find {
                    it is PartyAnchorActivity
                }
                //如果当前是通话状态，但是通话页面没有出现说明出现状态错乱
                if (partyAnchorActivity == null) {
                    gotoCallApply(needAgree, callBean)
                }
            }

            LiveConst.State.ONLY_LIVE -> {
                //无视
            }
        }
    }

    private fun gotoCallApply(needAgree: Boolean, callBean: CallSignalingMessage) {
        Router.builder(RoutePath.CALL_VIDEO_ACTIVITY)
            .withBoolean(LiveConst.Params.CALL_NEED_AGREE, needAgree)
            .withInt(LiveConst.Params.CALL_ROLE, LiveConst.CallRole.ANSWER)
            .withAny(LiveConst.Params.CALL_MESSAGE, callBean)
            .navigation()

        EventBus.getDefault().post(CallEndEvent())
    }

    private fun resolvedMsgId(argument: DataArgument): Boolean {
        val msgId = argument.getMsgId() ?: return true

        return !msgIdList.add(msgId)
    }

    companion object {

        val commands = setOf(
            COMMAND_CALL_START,
            COMMAND_CALL_START_WAIT,
            COMMAND_CALL_ANSWER,
            COMMAND_CALL_CANCEL,
            COMMAND_CALL_NO_ANSWER,
            COMMAND_CALL_REFUSE,
            COMMAND_CALL_END,
            COMMAND_LIVE_MESSAGE,
        )

        val publicMessages = setOf(
            LIVE_TOAST_MESSAGE,
            LIVE_NOTICE_MESSAGE,
        )
    }
}